import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tender_flutter/constant/app_config.dart';
import 'package:tender_flutter/constant/app_constant.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/common/api/api_common.dart';
import 'package:tender_flutter/page/home/model/city_entity.dart';
import 'package:tender_flutter/page/home/model/common_tag_model.dart';
import 'package:tender_flutter/page/supplier/api/api_supplier.dart';
import 'package:tender_flutter/page/supplier/item/supplier_list_cell.dart';
import 'package:tender_flutter/page/supplier/model/supplier_entity.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/widgets/drop_down_menu/drop_down_address_widget.dart';
import 'package:tender_flutter/widgets/drop_down_menu/drop_dpwm_list_widget.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';

class SupplierListPage extends StatefulWidget {
  /// 供应商类型 参见：AppConstant
  final int supplietType;

  /// 是否展示筛选菜单
  final bool isShowFilterMenu;

  final String keyword;

  const SupplierListPage(
      {Key key,
      this.supplietType = AppConstant.SUPPLIER_ALL,
      this.isShowFilterMenu = false,
      this.keyword})
      : super(key: key);

  @override
  SupplierListPageState createState() => SupplierListPageState();
}

class SupplierListPageState extends State<SupplierListPage>
    with AutomaticKeepAliveClientMixin {
  List<String> _dropDownHeaderItemStrings = ['全国', '类型', '行业'];

  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  GlobalKey _stackKey = GlobalKey();

  LoadState _loadState = LoadState.State_Loading;

  Future<ApiResponse<SupplierEntity>> _listFuture;

  Future<List<CommonTagModel>> _filterIndustryFuture;

  String keyword;

  int page = AppConfig.page;

  int pageCount = AppConfig.pageCount;

  CityEntity _selectCityModel;
  CommonTagModel _selectIndustryModel;
  CommonTagModel _selectTypeModel;

  /// 列表数据
  List<SupplierList> _listDatas = [];

  /// 行业类别
  List<CommonTagModel> _industryDatas = [];

  /// 类型数据
  List<CommonTagModel> _typeDatas;

  /// 手动刷新数据
  void manualRefersh() {
    if (_loadState == LoadState.State_Success && _refreshController != null) {
      _refreshController.requestRefresh();
    } else {
      _onRefresh();
    }
  }

  ///下拉刷新
  void _onRefresh() {
    page = 1;
    setState(() {
      _listFuture = _getData();
    });
  }

  /// 加载更多
  void _onLoading() {
    page += 1;
    setState(() {
      _listFuture = _getData();
    });
  }

  /// 获取行业类别
  Future<List<CommonTagModel>> _getIndustryCategory() async {
    if (_industryDatas != null && _industryDatas.isNotEmpty) {
      return _industryDatas;
    }
    var response =
        await ApiSupplier.getSupplierIndustryCategory<CommonListTagModel>();
    _industryDatas = response.result.xList;

    for (CommonTagModel tagModel in _industryDatas) {
      tagModel.isSelected = false;
    }
    _industryDatas.insert(0,
        CommonTagModel(strId: "0", title: "全部", value: "", isSelected: true));
    return _industryDatas;
  }

  /// 获取数据
  Future<ApiResponse<SupplierEntity>> _getData() async {
    var response = await ApiSupplier.getSupplierList<SupplierEntity>(
      areaCode: _selectCityModel != null ? _selectCityModel.id : null,
      industryId: _selectIndustryModel != null ? _selectIndustryModel.id : null,
      type:
          _selectTypeModel != null ? _selectTypeModel.id : widget.supplietType,
      keyword: keyword,
      page: page,
      pageCount: pageCount,
    );
    return response;
  }

  FutureBuilder<ApiResponse<SupplierEntity>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _listFuture,
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<SupplierEntity>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              SupplierEntity entity = snapshot.data.result;
              if (snapshot.data.status == Status.SUCCESS) {
                List temps = entity.xList == null ? [] : entity.xList;
                page == AppConfig.page
                    ? _listDatas = temps
                    : _listDatas += temps;
                if (_listDatas.isEmpty) {
                  _loadState = LoadState.State_Empty;
                } else {
                  _loadState = LoadState.State_Success;
                }
              } else {
                _loadState = LoadState.State_Error;
              }
            } else if (snapshot.hasError) {
              _loadState = LoadState.State_Error;
            }

            /// 结束刷新，处理分页
            if (_listDatas.length % AppConfig.pageCount != 0) {
              _refreshController.loadNoData();
            } else {
              if (_refreshController.isLoading) {
                _refreshController.loadComplete();
              }
            }
            if (_refreshController.isRefresh) {
              _refreshController.refreshCompleted(resetFooterState: true);
            }
          }

          return LoadStateLayout(
            state: _loadState,
            successWidget: _initListView(),
          );
        });
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _typeDatas = [
      CommonTagModel(
          strId: AppConstant.SUPPLIER_ALL.toString(),
          title: "全部",
          isSelected: true),
      CommonTagModel(
          strId: AppConstant.SUPPLIER_PERSION.toString(),
          title: "个人供应商",
          isSelected: false),
      CommonTagModel(
          strId: AppConstant.SUPPLIER_BUSINESS.toString(),
          title: "企业供应商",
          isSelected: false)
    ];
    keyword = widget.keyword;
    _listFuture = _getData();
    _filterIndustryFuture = _getIndustryCategory();
  }

  @override
  Widget build(BuildContext context) {
    return widget.isShowFilterMenu ? _initDorpMenu() : _buildFutureBuilder();
  }

  /// 筛选菜单
  Widget _initDorpMenu() {
    return Stack(
      key: _stackKey,
      children: <Widget>[
        Column(
          children: <Widget>[
            // 下拉菜单头部
            GZXDropDownHeader(
              height: ScreenAdapter.height(90),
              // 下拉的头部项，目前每一项，只能自定义显示的文字、图标、图标大小修改
              items: [
                GZXDropDownHeaderItem(_dropDownHeaderItemStrings[0]),
                GZXDropDownHeaderItem(_dropDownHeaderItemStrings[1]),
                GZXDropDownHeaderItem(_dropDownHeaderItemStrings[2]),
              ],
              // GZXDropDownHeader对应第一父级Stack的key
              stackKey: _stackKey,
              // controller用于控制menu的显示或隐藏
              controller: _dropdownMenuController,
              // 当点击头部项的事件，在这里可以进行页面跳转或openEndDrawer
              onItemTap: (index) {},
              // 文字样式
              style: TextStyle(
                  color: ThemeColors.colorType1,
                  fontSize: ScreenAdapter.sp(28)),
              // 下拉时文字样式
              dropDownStyle: TextStyle(
                fontSize: ScreenAdapter.sp(28),
                color: ThemeColors.colorType6,
              ),
              // 图标颜色
              iconColor: ThemeColors.colorType7,
              // 下拉时图标颜色
              iconDropDownColor: ThemeColors.colorType6,
            ),
            Expanded(child: _buildFutureBuilder())
          ],
        ),
        //下拉菜单
        GZXDropDownMenu(
          // controller用于控制menu的显示或隐藏
          controller: _dropdownMenuController,
          // 下拉菜单显示或隐藏动画时长
          animationMilliseconds: 300,
          dropdownMenuChanging: (isShow, index) {},
          dropdownMenuChanged: (isShow, index) {},
          // 下拉菜单，高度自定义，你想显示什么就显示什么，完全由你决定，你只需要在选择后调用_dropdownMenuController.hide();即可
          menus: [
            GZXDropdownMenuBuilder(
                dropDownHeight: 40 * 7.0,
                dropDownWidget: FutureBuilder(
                    future: ApiCommon.getCityDatas(),
                    builder: (BuildContext context,
                        AsyncSnapshot<List<CityEntity>> snapshot) {
                      if (snapshot.hasData) {
                        return DropMenuAddressWidget(
                          cityDatas: snapshot.data,
                          selectCityCallback:
                              (levelIndex, itemIndex, cityModel) {
                            if (levelIndex == 1) {
                              _selectCityModel = cityModel;
                              _dropDownHeaderItemStrings[0] = cityModel.title;
                              _dropdownMenuController.hide();
                              manualRefersh();
                            }
                            setState(() {});
                          },
                        );
                      } else {
                        return Container();
                      }
                    })),
            GZXDropdownMenuBuilder(
                dropDownHeight: ScreenAdapter.height(90) * 3,
                dropDownWidget: DropDownListWidget(
                  listDatas: _typeDatas,
                  selectListItemCallback: (itemIndex, tagModel) {
                    _selectTypeModel = tagModel;
                    _dropDownHeaderItemStrings[1] =
                        _selectTypeModel.title == '全部'
                            ? '类型'
                            : _selectTypeModel.title;
                    _dropdownMenuController.hide();
                    manualRefersh();
                    // setState(() {});
                  },
                )),
            GZXDropdownMenuBuilder(
                dropDownHeight: ScreenAdapter.height(80) * 6,
                dropDownWidget: FutureBuilder(
                    future: _filterIndustryFuture,
                    builder: (BuildContext context,
                        AsyncSnapshot<List<CommonTagModel>> snapshot) {
                      if (snapshot.hasData) {
                        print(snapshot.data.length);
                        return DropDownListWidget(
                          listDatas: snapshot.data,
                          selectListItemCallback: (itemIndex, tagModel) {
                            _selectIndustryModel = tagModel;
                            _dropDownHeaderItemStrings[2] =
                                _selectIndustryModel.title == '全部'
                                    ? '行业类别'
                                    : _selectIndustryModel.title;
                            _dropdownMenuController.hide();
                            manualRefersh();
                            // setState(() {});
                          },
                        );
                      } else {
                        return Container();
                      }
                    })),
          ],
        ),
      ],
    );
  }

  /// 主体内容列表
  Widget _initListView() {
    return Container(
        margin: EdgeInsets.only(
            top: widget.isShowFilterMenu ? ScreenAdapter.height(15) : 0),
        child: SmartRefresher(
            controller: _refreshController,
            enablePullUp: true,
            enablePullDown: true,
            onLoading: _onLoading,
            onRefresh: _onRefresh,
            child: ListView.separated(
              itemCount: _listDatas.length,
              itemBuilder: (BuildContext context, int index) {
                SupplierList model = _listDatas[index];
                return SupplierListCell(
                    data: model,
                    onTap: () {
                      LRouter.navigatorCtx(context).push(
                          Routes.supplierDetailPage,
                          arguments: SupplierDetailPageArguments(
                              supplierId: model.id));
                    });
              },
              separatorBuilder: (BuildContext context, int index) {
                return Divider(
                  height: ScreenAdapter.height(15),
                  color: ThemeColors.colorType11,
                );
              },
            )));
  }
}
